package irio.pythcal;



import android.graphics.DashPathEffect;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.MotionEvent;
import android.view.View.OnTouchListener;
import android.widget.EditText;



public class PaintView extends Preview implements OnTouchListener  {
	private Paint paint = new Paint();
    private Paint paintLine = new Paint();
    private Paint paintLine2 = new Paint();
    private Shape shape = new Shape();

    
    
    // Links to scale dialog
	
    public AlertDialog scaleDialog;
    public EditText edtScale;
    
    public Shape getShape() {
    	return shape;
    }

    public void setCamera() {
    	
    	if (cameraEnabled) {
    		start(); 
            setBackgroundColor(Color.TRANSPARENT);
            shape.setupPaintsCamera();
        	paint.setColor(Color.WHITE);
    	}
    	if (!cameraEnabled) {
    		stop();  
            //mCamera.release();
            setBackgroundColor(Color.WHITE);
            shape.setupPaints();
        	paint.setColor(Color.BLACK);
    	}
    
    }
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
    	super.surfaceCreated(holder);
    	setCamera();
    	
    }
    
    private void setup() {
    	paint.setColor(Color.BLACK);
        paint.setAntiAlias(true);

        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(3.0f);

        paintLine.setColor(Color.GRAY);
        paintLine.setAntiAlias(true);
        paintLine.setStrokeWidth(1.0f);
        DashPathEffect dashPath = new DashPathEffect(new float[]{20,5}, 1);
        paintLine.setPathEffect(dashPath);

        paintLine2.setColor(Color.LTGRAY);
        paintLine2.setAntiAlias(true);
        paintLine2.setStrokeWidth(0.5f);
        paintLine2.setPathEffect(dashPath);
    }
    
    public PaintView(Context context) {
        super(context);
        setup();
        shape.createShape(3); // 
        this.setOnTouchListener(this);
        setFocusable(true);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {  
    	super.surfaceDestroyed(holder);
 
    }  

    
	// Move the particle
    private void performMoveParticle() {
    	if (PythCal.cont.moveParticle==null)
    		return;
    	Vec dir = PythCal.cont.currentPos.sub(PythCal.cont.localCenter);
    	PythCal.cont.moveParticle.P = dir.norm();
    }
    
    // Find a particle	
    private Particle findParticle() {
    	Particle ret = null;
    	for (Particle p : shape.getList()) {
    		Vec v = shape.getRealPos(p);
    		if (v.sub(PythCal.cont.currentPos).len()<4.0*PythCal.cont.circleSize)
    			ret = p;
    	}
    	return ret;
    }
    
    // Initialize the scale dialog, set textx
    private void scaleDialog(float length) {
    	PythCal.cont.tempScale = length;
    	edtScale.setText("" + length*PythCal.cont.visualScale);
    	scaleDialog.show();
    }
    
    // Click on a line

    
    private void findLine() {
    	if (PythCal.cont.moveParticle!=null)
    		return;
    	for (int i=0;i<shape.getList().size();i++) {
    		shape.findNeighbourParticles(i);

    		float len = PythCal.cont.p1.P.sub(PythCal.cont.p0.P).len();
    		Vec cen = (PythCal.cont.p0.P.add(PythCal.cont.p1.P)).mul(0.5f);
    		Vec pos =  cen.mul(PythCal.cont.scale).add(PythCal.cont.localCenter);	

    		if (pos.sub(PythCal.cont.currentPos).len()<2.0*PythCal.cont.circleSize)
    			scaleDialog(len);
    	}
    }
    
    
    public boolean onTouch(View v, MotionEvent event) {
    	//FrameLayout.LayoutParams par = (LayoutParams) v.getLayoutParams(); 
    	PythCal.cont.currentPos.x = event.getX();
    	PythCal.cont.currentPos.y = event.getY();
		

    	switch (event.getAction()) {
    		case MotionEvent.ACTION_DOWN: {
    			PythCal.cont.moveParticle = findParticle();
    			findLine();
    		}
/*    		case MotionEvent.ACTION_UP: {
    			//moveParticle = null;
    		}*/
    	}
		performMoveParticle();
		// important to return true!
		return true;
    }
    
    void drawGrid(Canvas canvas) {
    	Paint p; 
    	int W = 10;
    	int w = 1000;
    	for (int i=0;i<W;i++) {
    		float px = PythCal.cont.localCenter.x+ (i-W/2)*0.5f*PythCal.cont.scale;
    		float py = PythCal.cont.localCenter.y+ (i-W/2)*0.5f*PythCal.cont.scale;
    		if (i==W/2) p = paintLine; // center drawn darker
    		else p = paintLine2;
    		canvas.drawLine(px,-w,px,w,p);
    		canvas.drawLine(-w,py,w,py,p);
    	}
    	    	
    }
    
    // set visual scale from input
    public void setVisualScale(String input) {
		try {
			PythCal.cont.visualScale = Float.valueOf(input);
			PythCal.cont.visualScale/=PythCal.cont.tempScale;
		} catch (Exception e) {
			
		}
	}
    
    private void update() {
    	PythCal.cont.center.x = this.getWidth()/2;
    	PythCal.cont.center.y = this.getHeight()/2;

    	// set scale from window width / height
    	PythCal.cont.scale = Math.min(getWidth(), getHeight())*PythCal.cont.initialScale;
    	PythCal.cont.circleSize = getWidth()*PythCal.cont.initialCircleSize;
    	PythCal.cont.windowWidth = getWidth();
    	PythCal.cont.windowHeight = getHeight();
    	
    	// from zoom
    	float len = (shape.getMaxAngle());
    	float max = 160;
    	if (len> max-5)
    		len = max - 5;

    	PythCal.cont.scale+=1000.0f/(Math.abs(len-max));
    	PythCal.cont.scale*=(1.5+PythCal.cont.zoom);

    	//Toast.makeText(getContext(), "" + len, 100);

    	// set the local center
    	PythCal.cont.localCenter = PythCal.cont.center.sub((shape.getPointCenter()).mul(PythCal.cont.scale)).sub(new Vec(0,20,0));
    	
    }
    
    @Override
    public void onDraw(Canvas canvas) {

    	update();
    	
    	if (Container.settings[Container.DRAW_GRID])
    		drawGrid(canvas);

    	if (Container.settings[Container.DRAW_CIRCLE])
    		canvas.drawCircle(PythCal.cont.localCenter.x, PythCal.cont.localCenter.y, PythCal.cont.scale, paint);

    	shape.render(canvas, PythCal.cont.localCenter, PythCal.cont.scale, PythCal.cont.circleSize, new Vec(00, getHeight()-40,0));

    	try {  
    		Thread.sleep(5);  
    	} catch (InterruptedException e) { }
    	      
    	 invalidate();  // Force a re-draw
    }

}

